#include "SipHandleMgr.hpp"

#include "WTResipDll/SipDebugInfo.hpp"

//#define SIPHANDLEMGR_CAPACITY 2048

namespace wtsxsip{

const uint32_t CSipHandleMgr::INVALID_HANDLE = 0;


CSipHandleMgr::CSipHandleMgr(void): m_counter(1){}

CSipHandleMgr::~CSipHandleMgr(void){}


uint32_t CSipHandleMgr::generateHandle()
{
    uint32_t rtHandle = INVALID_HANDLE;
    if (!m_recycler.empty()){
        boost::mutex::scoped_lock lock(m_RecyclerMutex);
        std::set<uint32_t>::iterator it;
        it = m_recycler.end();
        rtHandle = *(it--);
        m_recycler.erase(it);
    } else {
        rtHandle = m_counter++;
    }
    return rtHandle;
}


bool CSipHandleMgr::recycleHandle(uint32_t hd)
{
    boost::mutex::scoped_lock lock(m_RecyclerMutex);
    std::pair<std::set<uint32_t>::iterator, bool> ret;
    ret = m_recycler.insert(hd);
    if (!ret.second){
        ERROR_LINE("Handle had been recycled.");
        return false;
    }
    return true;
}


}//namespace

